<template>
  <div class="app-container">
    <div class="filter-container">
      <el-input v-model="listQuery.code" placeholder="请输入兑换码" style="width: 200px" class="filter-item" @keyup.enter="handleFilter" />
      <el-select v-model="listQuery.membershipType" placeholder="会员类型" clearable style="width: 150px" class="filter-item">
        <el-option label="月会员" value="vip_month" />
        <el-option label="季会员" value="vip_quarter" />
        <el-option label="年会员" value="vip_year" />
      </el-select>
      <el-select v-model="listQuery.status" placeholder="兑换码状态" clearable style="width: 150px" class="filter-item">
        <el-option label="未使用" value="active" />
        <el-option label="已使用" value="used" />
        <el-option label="已过期" value="expired" />
      </el-select>
      <el-button class="filter-item" type="primary" icon="Search" @click="handleFilter">搜索</el-button>
      <el-button class="filter-item" type="warning" icon="Refresh" @click="handleRefresh">重置刷新</el-button>
      <el-button class="filter-item" type="success" icon="Plus" @click="handleCreate">新增兑换码</el-button>
    </div>

    <el-table v-loading="listLoading" :data="list" element-loading-text="Loading..." border fit highlight-current-row>
      <el-table-column align="center" type="index" label="序号" width="80">
        <template #default="scope">
          {{ (listQuery.pageIndex - 1) * listQuery.pageSize + scope.$index + 1 }}
        </template>
      </el-table-column>
      <el-table-column label="兑换码" align="center">
        <template #default="scope">
          <el-tag type="info" size="small">{{ scope.row.code }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="可兑换会员类型" align="center" width="150">
        <template #default="scope">
          <el-tag :type="getMemberTypeTagType(scope.row.membershipType)">
            {{ getMemberTypeLabel(scope.row.membershipType) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="兑换码状态" align="center" width="120">
        <template #default="scope">
          <el-tag :type="getStatusTagType(scope.row.status)">
            {{ getStatusLabel(scope.row.status) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="兑换码使用用户" align="center" width="150">
        <template #default="scope">
          {{ scope.row.usedUserName || '-' }}
        </template>
      </el-table-column>
      <el-table-column label="创建时间" align="center" width="180">
        <template #default="scope">
          {{ scope.row.createdAt }}
        </template>
      </el-table-column>
      <el-table-column label="兑换时间" align="center" width="180">
        <template #default="scope">
          {{ scope.row.usedAt }}
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" width="200">
        <template #default="scope">
          <el-button size="small" type="danger" @click="handleDelete(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- <pagination :total="total" v-model:page="listQuery.pageIndex" v-model:limit="listQuery.pageSize" @pagination="getList" /> -->
    <el-pagination style="margin-top: 15px; background: #fff; padding: 10px" :page-size="listQuery.pageSize" @change="handlePageChange" background layout="prev, pager, next" :total="total" />

    <!-- 新增/编辑兑换码弹窗 -->
    <ExchangeCodeDialog v-model="dialogVisible" :exchange-code="currentExchangeCode" @success="handleDialogSuccess" />
  </div>
</template>

<script setup>
  import { ref, reactive, onMounted } from 'vue';
  import { ElMessage, ElMessageBox } from 'element-plus';
  import ExchangeCodeDialog from './components/ExchangeCodeDialog.vue';
  import { getExchangeCodeList, deleteExchangeCode } from '@/api/exchangeCode';

  const list = ref([]);
  const total = ref(0);
  const listLoading = ref(true);
  const dialogVisible = ref(false);
  const currentExchangeCode = ref(null);

  const listQuery = reactive({
    pageIndex: 1,
    pageSize: 15,
    code: '',
    membershipType: '',
    status: ''
  });

  const getList = async () => {
    listLoading.value = true;
    try {
      const response = await getExchangeCodeList(listQuery);
      if (response.code === 200) {
        list.value = response.data.list;
        total.value = response.data?.pagination?.total ?? 0;
      }
    } catch (error) {
      console.error('获取兑换码列表失败:', error);
      ElMessage.error('获取兑换码列表失败');
    } finally {
      listLoading.value = false;
    }
  };

  const handleFilter = () => {
    listQuery.pageIndex = 1;
    getList();
  };

  const handlePageChange = page => {
    listQuery.pageIndex = page;
    getList();
  };

  const handleCreate = () => {
    currentExchangeCode.value = null;
    dialogVisible.value = true;
  };

  const handleDelete = row => {
    ElMessageBox.confirm(`确定要删除兑换码"${row.code}"吗？`, '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }).then(async () => {
      try {
        const response = await deleteExchangeCode(row._id);
        if (response.code === 200) {
          ElMessage.success('删除成功');
          getList();
        } else {
          ElMessage.error(response.msg || '删除失败');
        }
      } catch (error) {
        console.error('删除兑换码失败:', error);
        ElMessage.error('删除失败');
      }
    });
  };

  const handleRefresh = () => {
    listQuery.pageIndex = 1;
    listQuery.pageSize = 15;
    listQuery.code = '';
    listQuery.membershipType = '';
    listQuery.status = '';
    getList();
  };

  const handleDialogSuccess = () => {
    dialogVisible.value = false;
    getList();
  };

  const getMemberTypeLabel = type => {
    const typeMap = {
      vip_month: '月会员',
      vip_quarter: '季会员',
      vip_year: '年会员'
    };
    return typeMap[type] || type;
  };

  const getMemberTypeTagType = type => {
    const typeMap = {
      month: 'success',
      quarter: 'warning',
      year: 'danger'
    };
    return typeMap[type] || 'info';
  };

  const getStatusLabel = status => {
    const statusMap = {
      used: '已使用',
      expired: '已过期',
      active: '未使用'
    };
    return statusMap[status] || status;
  };

  const getStatusTagType = status => {
    const statusMap = {
      active: 'success',
      used: 'info',
      expired: 'danger'
    };
    return statusMap[status] || 'info';
  };

  onMounted(() => {
    getList();
  });
</script>

<style scoped>
  .filter-container {
    padding-bottom: 10px;
  }

  .filter-item {
    margin-right: 10px;
  }
</style>
